<template>
  <div class="category">
    <div class="search">
      <el-form ref="searchForm" v-loading="listLoading" :model="searchForm" inline>
        <el-form-item label="订单编号" prop="id">
          <el-input v-model.trim="searchForm.orderNo" placeholder="请输入订单编号" class="input" clearable />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-radio-group v-model="searchForm.orderStatus" @change="filter" size="medium">
            <el-radio-button :label="1">待接单</el-radio-button>
            <el-radio-button :label="2">已接单</el-radio-button>
            <el-radio-button :label="3">待确认</el-radio-button>
            <el-radio-button :label="4">已完成</el-radio-button>
            <el-radio-button :label="0">已取消</el-radio-button>
            <el-radio-button :label="5">异常订单</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <!-- <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model.trim="searchForm.nickName" placeholder="用户昵称" class="input" clearable />
        </el-form-item> -->

        <!-- <el-form-item>
          <el-button type="primary" size="medium" @click="searchData">
            搜索
          </el-button>
          <el-button type="primary" size="medium" @click="resetSearchData">
            重置
          </el-button>
        </el-form-item> -->
      </el-form>
    </div>

    <div class="app-container">
      <el-table v-loading="listLoading"
        :data="tableData"
        element-loading-text="Loading" border fit highlight-current-row>

        <el-table-column label="订单编号" align="center" width="130">
          <template slot-scope="scope">
            {{ scope.row.orderNo }}
          </template>
        </el-table-column>
        <el-table-column label="游戏类型" align="center">
          <template slot-scope="scope">
            {{ scope.row.gameType === 1 ? '端游' : '手游' }}
          </template>
        </el-table-column>
        <el-table-column label="游戏" align="center">
          <template slot-scope="scope">
            {{ findGame(scope.row.gameId).gameName }}
          </template>
        </el-table-column>
        <el-table-column label="商品" align="center" width="180">
          <template slot-scope="scope">
            {{ scope.row.idleId ? findIdle(scope.row.idleId).idleName : '' }}
          </template>
        </el-table-column>
        <el-table-column label="游戏账号" align="center" width="180">
          <template slot-scope="scope">
            {{ scope.row.gameAccount }}
          </template>
        </el-table-column>
        <el-table-column label="老板游戏Id" align="center" width="180">
          <template slot-scope="scope">
            {{ scope.row.laobanyouxiid }}
          </template>
        </el-table-column>
        <el-table-column label="订单金额" align="center">
          <template slot-scope="scope">
            {{ '￥' + Number(scope.row.price).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="打手佣金" align="center">
          <template slot-scope="scope">
            {{ '￥' + Number(scope.row.dashouyongjin).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="语音频道" align="center" width="180">
          <template slot-scope="scope">
            {{ scope.row.channel }}
          </template>
        </el-table-column>
        <el-table-column label="支付方式" align="center" width="180">
          <template slot-scope="scope">
            {{ scope.row.payment }}
          </template>
        </el-table-column>
        <el-table-column label="单排/双排" align="center" width="180">
          <template slot-scope="scope">
            {{ scope.row.playerNum === 1 ? '单排' : '双排' }}
          </template>
        </el-table-column>
        <el-table-column label="接单打手" align="center" width="180">
          <template slot-scope="scope">
            {{ formatDashou(scope.row.playerId) }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" width="180">
          <template slot-scope="scope">
            {{
              scope.row.orderStatus === 0 ? '已取消' :
              scope.row.orderStatus === 1 ? '待接单' :
                scope.row.orderStatus === 2 ? '已接单' :
                  scope.row.orderStatus === 3 ? '待确认' :
                    scope.row.orderStatus === 4 ? '已完成' : '异常订单'
            }}
          </template>
        </el-table-column>
        <el-table-column label="发单人" align="center" width="180">
          <template slot-scope="scope">
            {{ scope.row.userId ? findUser(scope.row.userId).nickName : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="180">
          <template slot-scope="scope">
            {{ formatDate(new Date(scope.row.createdAt).getTime()) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="250">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)"
              v-if="scope.row.orderStatus !== 0 && scope.row.orderStatus !== 3">编辑</el-button>

            <el-button v-if="scope.row.orderStatus === 3" size="mini" type="primary"
              @click="confirmOrder(scope.row)">确认订单</el-button>
            <el-button v-if="scope.row.orderStatus === 4 && !scope.row.amountStatus" size="mini" type="primary"
              @click="payToPlayerByOrder(scope.row)">结算订单</el-button>
            <el-button v-if="searchForm.orderStatus !== 5" size="mini" type="danger"
              @click="handleDel(scope.row)">删除</el-button>
            <el-button v-if="searchForm.orderStatus === 5" size="mini" type="danger"
              @click="handleCancelBackOrder(scope.row)">取消订单</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="打手上传资料" :visible.sync="centerDialogVisible" width="30%" center>
        <h3>打手图片</h3>
        <el-carousel trigger="click">
          <el-carousel-item v-for="item in orderItem.imgArr" :key="item">
            <img :src="item" style="width: 80%;" />
          </el-carousel-item>
        </el-carousel>
        <h3>打手备注</h3>
        <p>{{ orderItem.playerRemark }}</p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="wancheng">确 定</el-button>
        </span>
      </el-dialog>
      <div class="pagination">
        <el-pagination background :current-page.sync="searchForm.page" layout="total, prev, pager, next"
          :total="tableData.length" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script>
import { getUserList, deleteUser } from '@/api/user'
import { orderCaozuo } from '@/plugins/utils/caozuojilu'
import { formatTime } from '@/plugins/utils/timeUtils'
import { fuzzyMatch } from '@/plugins/utils/filterArray'
import userApi from '@/plugins/api/user'
import orderApi from '@/plugins/api/order' // 添加缺失的导入
import gameApi from '@/plugins/api/game'
import idleApi from '@/plugins/api/idle'
import dealApi from '@/plugins/api/deal'
import configApi from '@/plugins/api/config'

export default {
  name: 'UserList',
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success'
      }
      return statusMap[status]
    },
    statusFilterText(status) {
      const statusMap = {
        0: '禁用',
        1: '正常'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      count: 0,
      gameOptions: [],
      allUser: [],
      centerDialogVisible: false,
      searchForm: {
        orderStatus: 1,
        page: 1,
        pageSize: 10
      },
      idles: [],
      orderItem: {},
      qrDialogVisible: false,
      qrArr: [],
      config: [],
      tableData: []
    }
  },
  mounted() {
    this.getConfig()
    this.getIdleList()
    this.fetchData()
    this.getGameList()
    this.getAllUser()
  },
  methods: {
    filter() {
      if (this.searchForm.orderStatus === 5) {
        const now = Date.now();
        const oneHourInMs = 60 * 60 * 1000; // 1小时 = 60分钟 * 60秒 * 1000毫秒
        this.tableData = this.list.filter(item => item.orderStatus === 1 && now - new Date(item.createdAt).getTime() > oneHourInMs)
      }
      this.fetchData()
      // return fuzzyMatch(this.list, this.searchForm)
    },
    getFadanConfig() {
      const fadan = this.config.find(item => item.name === 'fadan')
      console.log(Number(fadan.value) / 100);

      return Number(fadan.value) / 100
    },
    async getConfig() {
      const res = await configApi.list()
      if (res.code === 200) {
        this.config = res.data
      } else {
        this.$message.error('获取系统配置出错')
      }
    },
    async getIdleList() {
      const res = await idleApi.list()
      console.log('res -> ', res);
      if (res.code === 200) {
        this.idles = res.data
      } else {
        this.$message.error('获取商品列表出错')
      }
    },

    formatDashou(playerId) {
      if (playerId) {
        const arr = playerId.split(',')
        return arr.length > 1 ? this.findUser(Number(arr[0])).nickName + ', ' + this.findUser(Number(arr[1])).nickName : this.findUser(Number(arr[0])).nickName
      }
      return '暂无打手接单'
    },

    async orderPay() {
      this.orderItem.amountStatus = true
      this.orderItem.jiesuanTime = new Date().getTime()
      for (let i = 0; i < this.qrArr.length; i++) {
        const user = this.qrArr[i]
        const amount = user.parent ? (Number(this.orderItem.dashouyongjin) / Number(this.orderItem.playerNum)) * 0.99 : (Number(this.orderItem.dashouyongjin) / Number(this.orderItem.playerNum))
        user.weijiesuan = Number(user.weijiesuan) - Number(amount)
        user.yijiesuan = Number(user.weijiesuan) + Number(amount)
        await userApi.update(user)
      }
      const res = await orderApi.modify(this.orderItem)
      if (res.code === 200) {
        await orderCaozuo.update(this.orderItem)
        this.$message.success('订单更新成功')
      } else {
        this.$message.success('订单更新失败')
      }
    },

    async handleCancelBackOrder(item) {
      const that = this
      const o = await orderApi.getById(item)
      if (o.code === 200) {
        const oo = o.data
        if (oo.orderStatus === 1 && !oo.playerId) {
          oo.orderStatus = 0
          const self = that.findUser(oo.userId)
          const res = await orderApi.modify(oo)
          if (res.code === 200) {
            const dealObj = {
              userId: self.id,
              value: `${Number(oo.price)}`,
              type: 1,
              createTime: new Date().getTime(),
              orderNo: item.orderNo
            }
            self.balance = Number(self.balance) + Number(oo.price)
            const userRes = await userApi.update(self)
            if (userRes.code === 200) {
              await dealApi.modify(dealObj)
              await orderCaozuo.update(oo)
              that.$message.success('取消订单成功')
              that.getOrderList()
            }
          } else {
            that.$message.error(res.msg)
          }
        } else {
          that.$message.error(o.msg)
        }
      } else {
        that.$message.fail(o.msg)
      }
    },

    async wancheng() {
      const that = this
      that.orderItem.orderStatus = 4
      const res = await orderApi.modify(that.orderItem)
      if (res.code === 200) {
        await orderCaozuo.update(that.orderItem)
        that.$message.success('订单更新成功')
        that.centerDialogVisible = false
      } else {
        that.$message.success('订单更新失败')
      }
    },

    payOrderShow(row) {
      if (row.orderStatus === 4) {
        if (new Date().getTime() >= Number(row.wanchengTime)) {
          return true
        }
        return false
      }
      return false
    },

    async payToPlayer(player, days, playerNum, dashouyongjin) {
      console.log('player -> ', player);

      const that = this
      let price = Number(dashouyongjin) / Number(playerNum)
      if (player.parent) {
        const yaoqingren = this.allUser.find(item => item.id === player.parent)
        if (days) {
          if (yaoqingren) {
            yaoqingren.weijiesuan = Number(price) * 0.01
          }
          player.weijiesuan = Number(price) * 0.99

        } else {
          if (yaoqingren) {
            yaoqingren.weijiesuan = Number(price) * 0.01
          }
          player.weijiesuan = Number(price) * 0.99
        }
        if (yaoqingren) {
          that.deal(yaoqingren, Number(price) * 0.01, days)
        }

        that.deal(player, Number(price) * 0.99, days)
      } else {
        if (days) {
          player.weijiesuan = price
        } else {
          player.weijiesuan = price
        }
        await that.deal(player, price, days)
      }
    },

    async deal(user, price, days = 0) {
      console.log('this is deal');

      // 添加防重复提交标记
      // if (user._isDealing) {
      //   console.log('该用户正在处理中，跳过重复提交');
      //   return;
      // }

      try {
        // user._isDealing = true;

        const dealobj = {
          userId: user.id,
          value: price,
          createTime: new Date().getTime(),
          type: 2,
          jiesuanTime: new Date().getTime() + (60 * 60 * 1000 * days)
        }

        console.log('user -> ', user.id, 'deal -> ', dealobj);

        const res = await dealApi.modify(dealobj)
        if (res.code === 200) {
          await userApi.update(user)
          this.$message.success(user.nickName + '结算成功')
        } else {
          this.$message.error('结算失败: ' + res.msg)
        }
      } catch (error) {
        console.error('deal处理出错:', error);
        this.$message.error('结算过程出错: ' + error.message)
      } finally {
        // 清除处理标记
        user._isDealing = false;
      }
    },

    formatDate(timestamp) {
      return formatTime(timestamp)
    },

    findGame(id) {
      return this.gameOptions.find(item => item.id === id)
    },

    findIdle(id) {
      console.log(id, ' obj->', this.idles.find(item => item.id === Number(id)));

      return this.idles.find(item => item.id === id)
    },

    findUser(id) {
      console.log(id, '-> ', this.allUser.find(item => item.id === id));

      return this.allUser.find(item => item.id === id)
    },

    async getGameList() {
      const res = await gameApi.list()
      console.log('res -> ', res);
      if (res.code === 200) {
        this.gameOptions = res.data
      } else {
        this.$message.error('获取游戏列表出错')
      }
    },

    async getAllUser() {
      const res = await userApi.all()
      console.log('getAllUser -> ', res);
      if (res.code === 200) {
        this.allUser = res.data
      } else {
        this.$message.error('获取用户列表出错')
      }
    },

    // 获取用户信息
    async fetchData() {
      try {
        this.listLoading = true
        const res = await orderApi.page({orderStatus: this.searchForm.orderStatus, page: (this.searchForm.page - 1), size: this.searchForm.pageSize})
        console.log('res ss -> ', res);
        this.list = res.data.content
        this.tableData = res.data.content
      } catch (err) {
        console.log(err)
      } finally {
        this.listLoading = false
      }
    },
    // 跳转编辑
    handleEdit(row) {
      localStorage.setItem('order', JSON.stringify(row))
      this.$router.push('/order/edit')
    },
    confirmOrder(row) {
      console.log(row);

      // localStorage.setItem('order', JSON.stringify(row))
      this.orderItem = row
      this.orderItem.imgArr = row.playerImg.split(',')
      this.centerDialogVisible = true
    },
    async payToPlayerByOrder(row) {
      const that = this
      console.log('payToPlayerByOrder 开始执行，参数:', row)
      that.orderItem = row
      const arr = row.playerId.split(',')
      console.log('解析的玩家ID:', arr)
      const idle = that.idles.find(item => item.id === row.idleId)
      console.log('找到的商品信息:', idle)
      let player1 = that.allUser.find(item => item.id === Number(arr[0]))
      console.log('找到的玩家1:', player1)
      let player2 = arr.length > 1 ? that.allUser.find(item => item.id === Number(arr[1])) : null
      console.log('找到的玩家2:', player2)
      console.log('准备调用 payToPlayer，参数:', {
        player: player1,
        days: Number(idle.day),
        playerNum: row.playerNum,
        dashouyongjin: row.dashouyongjin
      })
      await that.payToPlayer(player1, Number(idle.day), row.playerNum, row.dashouyongjin)
      if (player2 !== null) {
        await that.payToPlayer(player2, Number(idle.day), row.playerNum, row.dashouyongjin)
      }
      if (that.orderItem.userId) {
        let fadanren = that.allUser.find(item => item.id === Number(row.userId))
        await that.deal(fadanren, Number(row.price) * that.getFadanConfig())
      }
      row.amountStatus = 1

      const res = await orderApi.modify(row)
      console.log('订单更新结果:', res);

      if (res.code === 200) {
        await orderCaozuo.update(row)
        that.$message.success('订单结算成功')
      } else {
        that.$message.success('订单结算失败')
      }
    },
    // 删除用户
    handleDel(row) {
      try {
        this.$msgbox
          .confirm('确定需要删除这个订单吗', '提示', {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'error'
          })
          .then(async () => {
            row.orderStatus = 9
            const res = await orderApi.modify(row)
            if (res.code === 200) this.$message.success('删除成功')
            await this.fetchData()
          })
      } catch (err) {
        this.$message.error(err)
      }
    },
    // 点击页面
    handleCurrentChange(page) {
      this.searchForm.page = page
      this.fetchData()
    },
    // 重置表单
    resetSearchData() {
      this.$refs['searchForm'].resetFields()
      // this.fetchData()
    }
  }
}
</script>

<style scoped lang="scss">
.category {
  box-sizing: border-box;
  margin: 24px;
}

.search {
  box-sizing: border-box;
  border-bottom: 1px solid #f0f0f0;
}

.pagination {
  display: flex;
  justify-content: center;
  margin: 24px 0;
}
</style>
